package gl.widget;

import gl.App;
import gl.android.biyiqing.R;
import gl.widget.GridLayout.LayoutParams;

import java.net.URI;
import java.util.ArrayList;

import android.content.Context;
import android.view.Gravity;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class AlbumControl {

	final int count = 7;
	/**
	 * 第二行第一个和第三行第1个占两列
	 */
	int[] rule_row = new int[] { 1, 1, 1, 1, 2, 2, 1 };
	ArrayList<String> urlList = new ArrayList<String>();
	private GridLayout gridLayout;
	private int width_item;
	private int height_item;
	private Context context;

	@SuppressWarnings("deprecation")
	public AlbumControl(GridLayout gridlayout) {
		this.gridLayout = gridlayout;
		this.context = gridlayout.getContext();
		gridLayout.setAlignmentMode(GridLayout.ALIGN_MARGINS);
		width_item = (gridlayout.getWidth() != 0 ? gridlayout.getWidth()
				: ((WindowManager) gridlayout.getContext()
						.getSystemService(Context.WINDOW_SERVICE))
						.getDefaultDisplay().getWidth()) / 3;
		height_item = width_item-width_item/45*10;

	}

	int index;
	int index_has_delete[];
	/**
	 * 表格位置索引
	 */
	int index_grid;
	public void addViewToGrid(String url,String hdUrl,Object id,OnClickListener toCoverView,OnLongClickListener mOnLongClickListener) {
		urlList.add(url);
		ImageView iv = new ImageView(context);
		iv.setOnClickListener(toCoverView);
		iv.setTag(hdUrl);
		iv.setScaleType(ScaleType.CENTER_CROP);
		iv.setOnLongClickListener(mOnLongClickListener);
//		iv.setBackgroundColor(Color.WHITE);
		LayoutParams params = new LayoutParams();
		params.setMargins(2, 2, 2, 2);
		params.width = width_item-2*2;
		params.height = height_item-2*2;

		int spceNumCurrentRow = rule_row[index % count];
		int postion_preraw = index_grid % gridLayout.getColumnCount();
//		System.out.println(String.format(
//				"index[%s]-Viewpostion[%s]-index_grid[%s]-rownum[%s]", index,
//				postion_preraw,index_grid, spceNumCurrentRow));
		GridLayout.Spec mSpec_c = GridLayout.spec(postion_preraw,
				spceNumCurrentRow);
		index_grid += rule_row[index % count];
		params.columnSpec = mSpec_c;
		params.setGravity(Gravity.FILL);
		iv.setLayoutParams(params);
		iv.setTag(R.id.img,id);
		gridLayout.addView(iv, params);
		renderUrl(url, iv);
		index++;
	}
	/**
	 * 使用URL渲染ImageView
	 * @see URI
	 * @param url
	 * @param iv
	 */
	public void renderUrl(String url, ImageView iv) {
		App.mFBitmap.display(iv, url);
	}
	public void removeAll() {
		gridLayout.removeAllViews();
		
	}

}
